#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

int main()
{
    char buffer[1024] = {0};
    if (access("fifo1", F_OK) == -1)
    {
        mkfifo("fifo1", 0644);
    }
    if (access("fifo2", F_OK) == -1)
    {
        mkfifo("fifo2", 0644);
    }
    // fifo1负责服务端向客户端发送，客户端读
    int fd1 = open("fifo1", O_WRONLY);
    int fd2 = open("fifo2", O_RDONLY);
    int cnt = 0;
    if (fd1 < 0 || fd2 < 0)
    {
        perror("file open fail");
        return 1;
    }
    int ret = fork();
    if (ret > 0)
    {
        while (1)
        {
            printf("Server#:\n");
            cnt = read(0, buffer, sizeof(buffer) - 1);
            size_t n = write(fd1, buffer, cnt);
            if (n < 0)
            {
                perror("write failed");
                break;
            }
        }
        close(fd1);
        wait(NULL);
    }
    else if (ret == 0)
    {
        while (1)
        {
            cnt = read(fd2, buffer, sizeof(buffer) - 1);
            if (cnt > 0)
            {
                buffer[cnt] = 0;
                printf("Client Say:\n");
                write(1, buffer, cnt);
                printf("Server#:\n");
            }
            else if (cnt == 0)
            {
                printf("client quit, me too!!\n");
                break;
            }
            else
            {
                perror("read failed");
                break;
            }
        }
        close(fd2);
    }
    else
    {
        perror("fork");
        return 1;
    }
    return 0;
}